package com.polaris.live.ui.live.proxy.gift

import android.animation.LayoutTransition
import android.content.Context
import android.widget.LinearLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.CollectionUtils
import com.google.common.cache.CacheBuilder
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.constant.LiveConst
import com.polaris.live.im.sfs.bean.live.SendLiveMessage
import com.polaris.live.im.sfs.bean.live.ext.MessageUserExtBean
import com.polaris.live.im.sfs.bean.live.payload.InviteGiftPayloadBean
import com.polaris.live.resp.bean.GiftNeedBean
import com.polaris.live.widget.gift.LiveGiftItemView
import java.util.concurrent.TimeUnit

/**
 * 礼物动画代理类
 *
 * @author Created by 半仙 on 2023/9/15/015 14:51
 */
class GiftAnimationProxy(
    lifecycleOwner: LifecycleOwner,
    private val mContext: Context,
    private val mLlGift: LinearLayout,
    private val mLiveName: String,
) {

    //是否清屏
    private var mClearScreen = false

    //头像点击回调
    private var mOnHeadOnClickListener: ((otherId: Long) -> Unit)? = null
    fun setOnHeadOnClickListener(click: (otherId: Long) -> Unit) {
        mOnHeadOnClickListener = click
    }

    private var isDestroy = false //是否已經銷毀

    init {
        mLlGift.layoutTransition = LayoutTransition().apply {
            setAnimateParentHierarchy(false)
            setAnimator(LayoutTransition.APPEARING, null)
            setAnimator(LayoutTransition.DISAPPEARING, null)
        }
        lifecycleOwner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    isDestroy = true
                    reset()
                }
            }
        })
    }

    //等待队列
    private val mGiftWaitList = mutableListOf<SendLiveMessage>()

    //当前展示的礼物队列         key值是用户id 加 礼物id
    private val mGiftShowMap = mutableMapOf<String, LiveGiftItemView>()

    //缓存上次送礼数量 缓存10秒 最多3个
    private val mGiftCache = CacheBuilder.newBuilder()
        .maximumSize(3)
        .expireAfterWrite(10, TimeUnit.SECONDS)
        .build<String, GiftNeedBean>()

    /**
     * 清屏 只保留自己的送礼特效
     */
    fun clearScreen(clearScreen: Boolean) {
        this.mClearScreen = clearScreen
        if (clearScreen) {
            val meUserId = UserManager.getUserId()
            val list = mGiftWaitList.filter {
                val tempExt = it.ext
                val tempPayLoad = it.payload
                if (tempExt == null || tempPayLoad == null) {
                    false
                } else {
                    val ext = tempExt as MessageUserExtBean
                    ext.user.userId == meUserId // 只保留符合条件的元素
                }
            }.toMutableList()
            mGiftWaitList.clear()
            mGiftWaitList.addAll(list)
        }
    }

    fun addAnimation(sendLiveMessage: SendLiveMessage) {
        if (isDestroy) {
            return
        }
        //先判断有没有数据
        val tempExt = sendLiveMessage.ext
        val tempPayLoad = sendLiveMessage.payload
        if (tempExt == null || tempPayLoad == null) {
            return
        }
        val ext = tempExt as MessageUserExtBean
        if (mClearScreen) {
            if (ext.user.userId != UserManager.getUserId()) {
                return
            }
        }
        val payload = tempPayLoad as InviteGiftPayloadBean
        //关注礼物不用飘这个
        if (payload.gift.type == LiveConst.GiftType.FOLLOWER_GIFT) {
            return
        }

        val key = "${ext.user.userId}${payload.gift.id}"

        val nowLiveGiftItemView = mGiftShowMap[key]
        //如果包含这个key且不在走关闭动画
        if (nowLiveGiftItemView != null && !nowLiveGiftItemView.startEndAnm) {
            nowLiveGiftItemView.dataChange(payload)
            updateCache(key)
            if (nowLiveGiftItemView.jobIsActive() == true) {
                nowLiveGiftItemView.jobCancel()
                nowLiveGiftItemView.animationDispatch()
            }
        } else {
            //不包含   判断当前是否展示3个礼物了
            if (mGiftShowMap.keys.size >= 2) {//已经展示3个了
                val cacheData = mGiftWaitList.find {
                    val cacheExt = it.ext as MessageUserExtBean
                    val cachePayload = it.payload as InviteGiftPayloadBean
                    val cacheKey = "${cacheExt.user.userId}${cachePayload.gift.id}"
                    cacheKey == key && cachePayload.nickname == payload.nickname//缓存里面有相同数据不新增 且送给人的名称相同
                }
                if (cacheData == null) {
                    mGiftWaitList.add(sendLiveMessage)
                } else { //有相同的合并数量
                    val lPayload = cacheData.payload as InviteGiftPayloadBean
                    val count = lPayload.giftCount + payload.giftCount
                    cacheData.payload = lPayload.copy(
                        giftCount = count
                    )
                }
            } else {
                var cacheData = mGiftCache.getIfPresent(key)
                var isCache = false
                if (cacheData != null) {
                    val endNum = cacheData.endNum
                    cacheData.endNum = endNum + payload.giftCount
                    isCache = true
                } else {
                    //添加到展示礼物队列
                    cacheData = addShowGift(payload)
                    mGiftCache.put(key, cacheData)
                }

                val liveGiftItemView = LiveGiftItemView(mContext).apply {
                    setData(
                        ext.user,
                        payload,
                        mLiveName,
                        key,
                        isCache,
                        cacheData,
                        this@GiftAnimationProxy
                    )
                    setOnGiftAnimationEnd {
                        mLlGift.post {
                            mGiftShowMap.remove(it)
                            mLlGift.removeView(this)
                            // 这里就是判断礼物列表里有数据啦更新了
                            if (!CollectionUtils.isEmpty(mGiftWaitList)) {
                                val data = mGiftWaitList[0]
                                mGiftWaitList.removeAt(0)

                                addAnimation(data)
                            }

                        }
                    }
                    setOnHeadOnClickListener {
                        mOnHeadOnClickListener?.invoke(it)
                    }
                    setOnNumListener {
                        updateCache(key)
                    }
                }
                mGiftShowMap[key] = liveGiftItemView

                mLlGift.addView(liveGiftItemView)

                liveGiftItemView.startAnimation()
            }
        }
    }

    private fun updateCache(key: String) {
        mGiftCache.getIfPresent(key)?.also {
            mGiftCache.put(key, it)
        }
    }

    //添加到礼物展示队列里
    private fun addShowGift(
        payload: InviteGiftPayloadBean,
    ): GiftNeedBean {
        return GiftNeedBean(1, payload.giftCount, payload.gift.id)
    }

    fun getEndTime(): Long {
        return if (!CollectionUtils.isEmpty(mGiftWaitList)) {
            REMOVE_VIEW_SHORT
        } else {
            REMOVE_VIEW_LONG
        }
    }

    fun reset() {
        mGiftWaitList.clear()
        mGiftShowMap.values.forEach {
            it.endAnimation()
        }
        mGiftShowMap.clear()
        mLlGift.removeAllViews()
    }

    companion object {

        const val LASTNUM = 10                  //最后的几个数字放大所有
        const val BIGTOSMALL = 500L             //数字放大
        const val TIME_STEP = 5
        const val HIGH_TIME_NUMBER = 250
        const val REMOVE_VIEW_LONG = 3000L      //移除延迟移除动画 3秒
        const val REMOVE_VIEW_SHORT = 1000L     //移除延迟移除动画 1秒
        const val MAX_TIME = 3500L              //最大时长3500
    }
}